package net.didactylos.helpline.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;

import org.hibernate.Session;

import net.didactylos.helpline.data.*;
import net.didactylos.helpline.servlet.EmailManager;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationError;

public class QueueAction extends HelplineActionBean
{
	
	private Queue queue;
	
	private List<Message> messages;
	
	private List<Message> approvals;
	
	private List<Conversation> conversations;
	
	private Queue emailQueue;
	
	private Queue checkQueue;

	public Queue getQueue()
	{
		return queue;
	}

	public void setQueue(Queue queue)
	{
		this.queue = queue;
	}

	@SuppressWarnings("unchecked")
	public List<Message> getMessages()
	{
		if ((messages == null))
		{
			Session session = getContext().getSession();
			EmailManager em = new EmailManager(session);
			
			messages = new ArrayList<Message>();
			try
			{
				em.checkInbox(messages, false);
			}
			catch (MessagingException e)
			{
				ValidationError error = new LocalizableError("emailFailure");
	            getContext().getValidationErrors().addGlobalError(error);
				e.printStackTrace();
			}
			
			//messages = em.getDefaultQueue().getMessages();
			
			messages = (List<Message>) getContext().getSession()
			.createQuery("from Message as msg where msg.queue.name = ? and msg.conversation.owner is null")
			.setParameter(0, "Email")
			.list();
			//session.getTransaction().commit();
		}
		return messages;
	}

	@SuppressWarnings("unchecked")
	public List<Conversation> getConversations()
	{
		if ((conversations == null) && (queue != null))
		{
			conversations = getContext().getSession()
			.createQuery("from Conversation as conv where conv.queue_id = ?")
			.setLong(0, queue.getId())
			.list();
		}
		return conversations;
	}
	
	@SuppressWarnings("unchecked")
	public List<Message> getApprovals()
	{
		if (approvals == null)
		{
			approvals = (List<Message>) getContext().getSession()
			.createQuery("from Message as msg where msg.queue.name = ? and msg.conversation.owner is null")
			.setParameter(0, "Check")
			.list();
		}
		return approvals;
	}

	public Queue getEmailQueue()
	{
		if (emailQueue == null)
		{
			emailQueue = (Queue) getContext().getSession()
			.createQuery("from Queue as queue where queue.name = ?")
			.setParameter(0, "Email")
			.uniqueResult();
		}
		return emailQueue;
	}

	public Queue getCheckQueue()
	{
		if (checkQueue == null)
		{
			checkQueue = (Queue) getContext().getSession()
			.createQuery("from Queue as queue where queue.name = ?")
			.setParameter(0, "Check")
			.uniqueResult();
		}
		return checkQueue;
	}
	
	
}
